<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-col :span="4" class="treetable">
        <el-button type="primary" class="v" @click="showaddCateDialogVIsible"
          >添加分类</el-button
        >
      </el-col>
      <!-- 表格区域 -->
      <Tree-table
        class="treetable"
        :data="cateList"
        :columns="columns"
        index-text="#"
        show-index
        :selection-type="false"
        :expand-type="false"
        border
        :show-row-hover="false"
      >
        <!-- 是否有效 -->
        <template v-slot:isOK="scoped">
          <!-- {{scoped.row}} -->
          <i
            class="el-icon-success"
            style="color: green"
            v-if="scoped.row.cat_deleted === false"
          ></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <!-- 排序 -->
        <template v-slot:port="scoped">
          <el-tag v-if="scoped.row.cat_level === '0'">一级</el-tag>
          <el-tag type="success" v-else-if="scoped.row.cat_level === '1'"
            >二级</el-tag
          >
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template v-slot:edit="scoped">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="enidFn(scoped.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteIdFn(scoped.row.cat_id)"
            >删除</el-button
          >
        </template>
      </Tree-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="70%"
      @close="addCateClose"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="addCateForm"
        :rules="addCateRules"
        ref="addCateForm"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="cascaderKeyID"
            :options="addCateList"
            :props="cascaderProps"
            @change="cascaderhandleChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateFn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改分类 -->
    <el-dialog title="修改分类" :visible.sync="editdialogVisible" width="70%">
      <el-form
        :model="enidFrom"
        :rules="editRules"
        ref="editCateForm"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="enidFrom.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 2,
      },
      // 保存商品分类
      cateList: [],
      total: 0,
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        // 是否有效
        {
          label: "是否有效",
          type: "template",
          template: "isOK",
        },
        // 权限
        {
          label: "排序",
          prop: "cat_level",
          type: "template",
          template: "port",
        },
        {
          label: "操作",
          type: "template",
          template: "edit",
        },
      ],
      // 添加分类对话框显示与隐藏
      addCateDialogVisible: false,
      // 添加分类表单
      addCateForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0, //默认一级分类
      },
      // 添加分类表单规则
      addCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      // 保存商品分类列表
      addCateList: [],
      // 内联选择器的配置对象
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true,
      },
      // 保存选择的id
      cascaderKeyID: [],
      // 修改分类对话框
      editdialogVisible: false,
      // 根据id查询数据保存
      enidFrom: {},
      editRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCate();
  },
  methods: {
    // 获取商品分类
    async getCate() {
      const { data: res } = await this.$axios.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类失败");
      this.cateList = res.data.result;
      this.total = res.data.total;
      // console.log(this.total);
    },
    //页数
    handleSizeChange(newpagesize) {
      //  console.log('size',newpagesize);
      this.queryInfo.pagesize = newpagesize;
      this.getCate();
    },
    handleCurrentChange(newnum) {
      // console.log("num", newnum);
      this.queryInfo.pagenum = newnum;
      this.getCate();
    },
    // 显示添加分类对话框
    showaddCateDialogVIsible() {
      this.getCateList();
      this.addCateDialogVisible = true;
    },
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$axios.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类列表失败");
      this.addCateList = res.data;
      // console.log(this.addCateList);
    },
    // 父级分类发生变化的时候
    cascaderhandleChange() {
      console.log(this.cascaderKeyID);
      if (this.cascaderKeyID.length > 0) {
        this.addCateForm.cat_pid =
          this.cascaderKeyID[this.cascaderKeyID.length - 1];
        this.addCateForm.cat_level = this.cascaderKeyID.length;
      } else {
        (this.addCateForm.cat_pid = 0), (this.addCateForm.cat_level = 0);
      }
      // console.log(this.addCateForm);
    },
    // 添加分类确认
    addCateFn() {
      // console.log(this.addCateForm);
      this.$refs.addCateForm.validate(async (vaild) => {
        if (!vaild) return this.$message.error("表单数据不合法");
        const { data: res } = await this.$axios.post("categories", {
          cat_pid: this.addCateForm.cat_pid,
          cat_name: this.addCateForm.cat_name,
          cat_level: this.addCateForm.cat_level,
        });
        // console.log(res);
        if (res.meta.status !== 201) return this.$message.error("添加分类失败");
        this.getCate();
        this.$message.success("添加分类成功");
        this.addCateDialogVisible = false;
      });
    },
    // 清空表单数据
    addCateClose() {
      this.$refs.addCateForm.resetFields();
      (this.cascaderKeyID = []),
        (this.addCateForm.cat_level = 0),
        (this.addCateForm.cat_pid = 0);
    },
    // 显示修改对话框
    async enidFn(id) {
      const { data: res } = await this.$axios.get("categories/" + id);
      // console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("根据id查询商品失败");
      this.enidFrom = res.data;
      // console.log(this.enidFrom);
      this.editdialogVisible = true;
    },
    // 根据id修改 cat_id
    saveEdit() {
      this.$refs.editCateForm.validate(async (vaild) => {
        if (!vaild) return this.$message.error("数据不合法");
        const { data: res } = await this.$axios.put(
          `categories/${this.enidFrom.cat_id}`,
          { cat_name: this.enidFrom.cat_name }
        );
        if (res.meta.status !== 200) return this.$message.error("修改数据失败");
        // console.log(res);
        this.getCate();
        this.$message.success("修改数据成功");
        this.editdialogVisible = false;
      });
    },
    // 根据id删除
    async deleteIdFn(id) {
      const res = await this.$confirm(
        "此操作将永久删除该商品分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // console.log(res);
      if (res !== "confirm") return this.$message.info("取消了删除操作");

      const { data: res1 } = await this.$axios.delete("categories/" + id);
      // console.log(res1);
      if(res1.meta.status !== 200) return this.$message.error('删除失败')
      this.getCate()
      this.$message.success('删除成功')
    },
  },
};
</script>

<style lang="less" scoped>
.treetable {
  margin-bottom: 20px !important;
}
.el-cascader {
  width: 100%;
}
</style>